<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card class="box-card">
      <el-alert
        title="添加商品信息"
        type="info"
        center
        show-icon>
      </el-alert>

      <!-- 步骤条 -->

      <el-steps :active="activeIndex - 0" finish-status="success" align-center style="margin:30px">
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <!-- 左侧标签栏 -->
      <el-form :model="updateForm" :rules="rules" ref="updateForm" label-position="left">
      <el-tabs
        :tab-position="tabPosition"
        v-model="activeIndex"
        :before-leave="beforeTabLeave"
        @tab-click="tabClicked"
        style="height: 500px;">
        <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="updateForm.goods_name" ></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="updateForm.goods_price" ></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="updateForm.goods_number" ></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="updateForm.goods_weight" ></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <!-- 三级分类 -->
                <el-cascader
                v-model="updateForm.goods_cat"
                :options="allType"
                :props="selectProps"
                @change="typeSelect"
                clearable></el-cascader>
            </el-form-item>
        </el-tab-pane>


        <el-tab-pane label="商品参数" name="1">
          <el-form-item :label="item.attr_name" v-for="item in manyTableData" :key="item.attr_id">
            <el-checkbox-group v-model="item.attr_vals" size="small">
              <el-checkbox :label="cb" v-for="(cb, i) in item.attr_vals" :key="i" border></el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="商品属性" name="2">
          <el-form-item :label="item.attr_name" v-for="item in onlyData" :key="item.attr_id">
            <el-input v-model="item.attr_vals"></el-input>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="商品图片" name="3">
          <!-- 这里要写全地址：因为这里发送的不是通过axios请求，是表单自带的请求方式 -->
          <el-upload
            class="upload-demo"
            action="http://127.0.0.1:8888/api/private/v1/upload"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :on-success="handleSuccess"
            :file-list="fileList"
            accept="image/jpeg, image/png"
            :headers="headerObj"
            list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <template #tip>
              <div class="el-upload__tip">
                只能上传 jpg/png 文件，且不超过 500kb
              </div>
            </template>
          </el-upload>
        </el-tab-pane>

        <el-tab-pane label="商品内容" name="4">
          <!-- 富文本编辑器 -->
          <!-- 这个高度样式要设在全局css里面 -->
          <ckeditor :editor="editor" v-model="editorData" :config="editorConfig"></ckeditor>

          <!-- 添加 -->
          <el-button @click="add" class="el_btn" type="primary">添加商品</el-button>
        </el-tab-pane>
      </el-tabs>
      </el-form>
    </el-card>

    <!-- 查看图片弹出框 -->
    <el-dialog
      title="图片预览"
      v-model="prevDialogVisible"
      width="70%"
      center>
      <img :src="prevPath" alt="">
    </el-dialog>
  </div>
</template>

<script>
import ClassicEditor from '@ckeditor/ckeditor5-build-classic';
import {ElMessage} from "element-plus";
import _ from 'lodash'

export default {
name: "add",
  data(){
  return{
    activeIndex:0,
    fileList:[],
    onlyData:[],
    manyTableData:[],
    tabPosition:'left',
    //设置请求头
    headerObj:{
      Authorization:sessionStorage.getItem('token')
    },
    pics:[],
    prevPath:'',
    prevDialogVisible:false,
    editor:ClassicEditor,
    editorData:'',
    editorConfig:{
      height:'350px'
    },rules:{
      goods_name: [
        { required: true, message:'请输入商品名称', trigger: 'blur' }
      ],
      goods_price: [
        { required: true, message:'请输入价格', trigger: 'blur' }
      ],
      goods_weight: [
        { required: true, message:'请输入重量', trigger: 'blur' }
      ],
      goods_number: [
        { required: true, message:'请输入数量', trigger: 'blur' }
      ]
    },
    updateForm:{
      goods_name:'',
      goods_price:'',
      goods_weight:'',
      goods_number:'',
      goods_cat:[],
      attrs:[],
      pics:[],
      goods_introduce:''
    },
    cat_id:[],
    allType:[],
    selectProps:{
      label:'cat_name',
      value:'cat_id',
      expandTrigger:'hover'
    },
  }
  },
  created() {
    this.getAllType();
  },
  methods:{
    getAllType() {
      this.axios.get('categories', {
        params: {
          type:3
        }
      }).then(resp => {
        if (resp.data.meta.status !== 200) return ElMessage.error(resp.data.meta.msg);
        this.allType = resp.data.data;
      }).catch(err => {
        console.log(err);
      })
    },
    //标签页的点击事件
    typeSelect() {
      //在发送请求获取数据之前，要先判断一下，有没有进行三级联动
      if (!this.updateForm.goods_cat || this.updateForm.goods_cat.length < 3) {
        ElMessage.warning('请选择三级分类');
        this.cat_id = [];
        return;
      }
    },
    //标签页离开之前触发钩子函数
    beforeTabLeave(activeName,oldActiveName){
      if( oldActiveName === '0' && this.updateForm.goods_cat.length !== 3 ){
        ElMessage.warning('请先选择商品分类');
        return false;
      }
    },
    //标签页页面的点击事件
    tabClicked(){
      //动态参数面板
      if( this.activeIndex === '1' ){
        //获取动态参数面板
        this.axios.get(`categories/${this.catId}/attributes`,{
          params:{
            sel:'many'
          }
        }).then(resp=>{
          //注意：这里的数据 attr_vals是一个字符串 ，而我们需要v-for循环，要数组
          resp.data.data.forEach(item=>{
            item.attr_vals = item.attr_vals.length === 0 ? [] : item.attr_vals.split(',');
          })
            //设置一个变量，用来控制input和按钮的显示
            this.manyTableData = resp.data.data;
          console.log(resp)
        }).catch(err=>{
          console.log(err)
        })
      }else if( this.activeIndex === '2'  ){
          //获取静态属性
          this.axios.get(`categories/${this.catId}/attributes`,{
            params:{
              sel:'only'
            }
          }).then(resp=>{
              this.onlyData = resp.data.data;
            console.log(this.onlyData)
            }).catch(err=>{
              console.log(err)
            })
        }
      },

    handlePreview(file){
      console.log(file);
      this.prevPath = file.response.data.url;
      this.prevDialogVisible = true;
    },
    handleRemove(file){
      let filePath = file.response.data.tmp_path;
      let index = this.pics.findIndex(temp=>
        temp === filePath
      )
        //不单单要删除网页上面的图片，pics这个数组里面的数据也要删除
      this.pics.splice(index,1);
      console.log(this.pics);
    },
    handleSuccess(resp){
      console.log(resp);
      //存一下
      this.pics.push(resp.data.tmp_path);
    },
    add(){
      this.$refs.updateForm.validate((valid)=>{
        if(valid){
          //深拷贝：可以拷贝全部，包括数组  npm i --save lodash
          let form = _.cloneDeep(this.updateForm);
          //Arrays.clone() 浅拷贝：只能拷贝当前对象下面的一层数据，如果有两层对象，第二层会直接复制过去
          form.goods_cat = form.goods_cat.join(',');
          //处理动态参数和静态参数
          this.manyTableData.forEach(item=>{
            let newInfo = {
              attr_id:item.attr_id,
              attr_vals:item.attr_vals
            }
            this.updateForm.attrs.push(newInfo);
          })
          //交接给form对象
          form.attrs = this.updateForm.attrs;
          console.log(form);
          //开始发送请求
          this.axios.post('goods',form).then(resp=>{
            if(resp.data.meta.status !== 201) return ElMessage.error('添加商品失败');
            ElMessage.success('添加商品成功');
            this.$router.push('/goods');
          }).catch(err=>{
            console.log(err);
          })
        } else {
          return false;
        }
      });
    }
  },
  //计算属性
  computed:{
  catId(){
    if( this.updateForm.goods_cat.length === 3 ){
      return this.updateForm.goods_cat[2];
    }
    return null;
  }
  }
}
</script>

<style scoped>

</style>
